package com.a2.appa3.ui.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.a2.appa3.R;
import com.a2.appa3.global.HttpAdress;
import com.a2.appa3.global.Info;
import com.a2.appa3.model.CustomObserver;
import com.a2.appa3.model.network.HttpJsonUtils;
import com.a2.appa3.model.network.entity.req.ResRoomInfo;
import com.a2.appa3.model.network.entity.req.changeNikeNameBean;
import com.a2.appa3.util.OnItemClickListener;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.shihao.library.XStatusBarHelper;

public class GroupManageActivity extends BaseActivitySimple {

    @BindView(R.id.ivback)
    ImageView ivback;
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.headerTitle)
    TextView headerTitle;
    @BindView(R.id.tvback)
    TextView tvback;
    @BindView(R.id.groundname)
    TextView groundname;
    @BindView(R.id.groundnikname)
    TextView groundnikname;
    @BindView(R.id.groundalluser)
    TextView groundalluser;
    @BindView(R.id.user_drop_out)
    TextView user_drop_out;
    @BindView(R.id.disbandgroup)
    TextView disbandgroup;
    @BindView(R.id.clearroomlist)
    LinearLayout clearroomlist;
    @BindView(R.id.reviewgroup)
    LinearLayout reviewgroup;
    @BindView(R.id.grounduserlist)
    RecyclerView grounduserlist;
    private Adapter adapter;
    private ArrayList<ResRoomInfo.DataBean.UListBean> list = new ArrayList();
    private boolean ismanage = false;//是不是管理员或房主
    private String roomId;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        if (Build.VERSION.SDK_INT >= 21) {
            //解决Android5.0以上，状态栏设置颜色后变灰的问题
            XStatusBarHelper.tintStatusBar(this, getResources().getColor(R.color.settingbg));
        }
        roomId = getIntent().getStringExtra("roomid");
        InitData();
        GridLayoutManager layoutManager = new GridLayoutManager(this, 5, LinearLayoutManager.VERTICAL, false);
        grounduserlist.setLayoutManager(layoutManager);
        adapter = new Adapter();
        grounduserlist.setAdapter(adapter);

    }

    /**
     * 解散群
     */
    private void disbandgroupclass() {
        HttpJsonUtils.getHttpApiInstance()
                .user_drop_outclass(HttpAdress.getuseAdress() + "api/chatapi/ChatRoom/releaseRoom", roomId, Info.Token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<changeNikeNameBean>() {
                    @Override
                    protected void onCustomNext(changeNikeNameBean resRoomInfo) {
                        if (resRoomInfo.getCode() == 0) {
                            Toast.makeText(GroupManageActivity.this, "解散成功", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(GroupManageActivity.this, "" + resRoomInfo.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }
                });
    }

    /**
     * 群成员退出群聊
     */
    private void user_drop_outclass() {
        HttpJsonUtils.getHttpApiInstance()
                .user_drop_outclass(HttpAdress.getuseAdress() + "api/chatapi/ChatRoom/outRoom", roomId, Info.Token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<changeNikeNameBean>() {
                    @Override
                    protected void onCustomNext(changeNikeNameBean resRoomInfo) {
                        if (resRoomInfo.getCode() == 0) {
                            Toast.makeText(GroupManageActivity.this, "退出成功", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(GroupManageActivity.this, "" + resRoomInfo.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        InitData();
    }

    //    roomId
    private void InitData() {
        HttpJsonUtils.getHttpApiInstance()
                .roomInfo(HttpAdress.getuseAdress() + "api/chatapi/ChatRoom/roomInfo", roomId, Info.Token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<ResRoomInfo>() {
                    @Override
                    protected void onCustomNext(ResRoomInfo resRoomInfo) {
                        if (resRoomInfo.code == 0) {
                            headerTitle.setText("");
                            tvback.setText("聊天信息(" + resRoomInfo.data.user_num + ")");
                            groundname.setText("" + resRoomInfo.data.room_name);
                            if (resRoomInfo.data.room_founder == Info.user.userId) {
                                ismanage = true;
                                user_drop_out.setVisibility(View.GONE);
                                disbandgroup.setVisibility(View.VISIBLE);

                            } else {
                                ismanage = false;
                                user_drop_out.setVisibility(View.VISIBLE);
                                disbandgroup.setVisibility(View.GONE);

                            }
                            list.clear();
                            list.addAll(resRoomInfo.data.u_list);
                            adapter.notifyDataSetChanged();
                        }


                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }
                });
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_group_manage;
    }

    @OnClick({R.id.back, R.id.groundalluser, R.id.groundname, R.id.groundnikname, R.id.clearroomlist, R.id.reviewgroup, R.id.user_drop_out, R.id.disbandgroup})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.groundalluser:
                Intent intent = new Intent(GroupManageActivity.this, ChatRoomlistActivity.class);
                intent.putExtra("grounpid", roomId);
                startActivity(intent);
                break;
            case R.id.groundname:

                break;
            case R.id.groundnikname:
                Intent intent1 = new Intent(GroupManageActivity.this, changeNikeDiolog.class);
                intent1.putExtra("grounpid", roomId);
                startActivity(intent1);
                break;
            case R.id.clearroomlist:
                Info.mdatas.clear();
                Toast.makeText(GroupManageActivity.this, "清除成功", Toast.LENGTH_SHORT).show();
                break;
            case R.id.reviewgroup:
                //审核加群的人
                Intent intent2 = new Intent(GroupManageActivity.this, ReviewListActivity.class);
                intent2.putExtra("grounpid", roomId);
                startActivity(intent2);
                break;
            case R.id.user_drop_out:
                user_drop_outclass();
                break;
            case R.id.disbandgroup:
                disbandgroupclass();
                break;
        }
    }

    class Adapter extends RecyclerView.Adapter<Adapter.MViewHolder>
            implements OnItemClickListener {
        @NonNull
        @Override
        public MViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
            return new MViewHolder(LayoutInflater.from(GroupManageActivity.this)
                    .inflate(R.layout.grounduseritem, viewGroup, false));
        }

        @Override
        public void onBindViewHolder(final MViewHolder holder, final int position) {
            if (position < list.size()) {
                if (list.get(position).user_id == Info.user.userId) {
                    groundnikname.setText(list.get(position).room_nickname);
                }
            }
            if (ismanage) {
                //管理员
                if (position == list.size()) {
                    //并且是管理员或者房主，才可以删除群成员
                    holder.user_name.setVisibility(View.GONE);
                    holder.user_img.setVisibility(View.GONE);
                    holder.addgrounduser.setVisibility(View.VISIBLE);
                    holder.addgrounduser.setImageResource(R.mipmap.removegrounduser);
                    holder.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(GroupManageActivity.this, UserSelectActivity.class);
                            intent.putExtra("roomid", roomId + "");
                            intent.putExtra("roomflag", false);//true是添加false是踢人
                            startActivity(intent);
                        }
                    });
                } else if (position == list.size() + 1) {
                    //所有人都可以添加群成员
                    holder.user_name.setVisibility(View.GONE);
                    holder.user_img.setVisibility(View.GONE);
                    holder.addgrounduser.setVisibility(View.VISIBLE);
                    holder.addgrounduser.setImageResource(R.mipmap.addgrounduser);
                    holder.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(GroupManageActivity.this, UserSelectActivity.class);
                            intent.putExtra("roomid", roomId + "");
                            intent.putExtra("roomflag", true);//true是添加false是踢人
                            startActivity(intent);
                        }
                    });
                } else {
                    holder.user_name.setVisibility(View.VISIBLE);
                    holder.user_img.setVisibility(View.VISIBLE);
                    holder.addgrounduser.setVisibility(View.GONE);
                    Glide.with(GroupManageActivity.this).load(HttpAdress.getuseAdress()
                            + list.get(position).img).error(R.mipmap.huihuadefaultpic).into(holder.user_img);
                    holder.user_name.setText(list.get(position).nickname);
                    holder.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(GroupManageActivity.this, SearchActivity.class);
                            intent.putExtra("username", list.get(position).user_id + "");
                            intent.putExtra("usertype", "users");
                            startActivity(intent);
                        }
                    });
                }

            } else {
                //普通用户
                if (position == list.size()) {
                    //所有人都可以添加群成员
                    holder.user_name.setVisibility(View.GONE);
                    holder.user_img.setVisibility(View.GONE);
                    holder.addgrounduser.setVisibility(View.VISIBLE);
                    holder.addgrounduser.setImageResource(R.mipmap.addgrounduser);
                    holder.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(GroupManageActivity.this, UserSelectActivity.class);
                            intent.putExtra("roomid", roomId + "");
                            intent.putExtra("roomflag", true);//true是添加false是踢人
                            startActivity(intent);
                        }
                    });
                } else {
                    holder.user_name.setVisibility(View.VISIBLE);
                    holder.user_img.setVisibility(View.VISIBLE);
                    holder.addgrounduser.setVisibility(View.GONE);
                    Glide.with(GroupManageActivity.this).load(HttpAdress.getuseAdress()
                            + list.get(position).img).error(R.mipmap.huihuadefaultpic).into(holder.user_img);
                    holder.user_name.setText(list.get(position).nickname);
                    holder.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(GroupManageActivity.this, SearchActivity.class);
                            intent.putExtra("username", list.get(position).user_id + "");
                            intent.putExtra("usertype", "users");
                            startActivity(intent);
                        }
                    });
                }
            }

        }

        @Override
        public int getItemCount() {
            //房主或管理员加2普通用户加1
            if (ismanage) {
                return list.size() + 2;
            } else {
                return list.size() + 1;
            }

        }

        @Override
        public void onItemClick(View view, int position) {

        }

        public class MViewHolder extends RecyclerView.ViewHolder {
            TextView user_name;
            ImageView addgrounduser, user_img;

            MViewHolder(View itemView) {
                super(itemView);
                user_name = (TextView) itemView.findViewById(R.id.user_name);
                addgrounduser = (ImageView) itemView.findViewById(R.id.addgrounduser);
                user_img = (ImageView) itemView.findViewById(R.id.user_img);
            }
        }
    }
}
